package config

import (
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/sirupsen/logrus"
	"log"
	"sync"
)

var minioClient *minio.Client
var once1 sync.Once // 确保初始化只执行一次的同步工具

// InitMinioClient Initialize minio client object.
func InitMinioClient(props *MinioProperties) {
	once1.Do(func() {
		client, err := minio.New(props.Endpoint, &minio.Options{
			Creds:  credentials.NewStaticV4(props.AccessKeyID, props.SecretAccessKey, ""),
			Secure: props.IsSecure,
		})
		if err != nil {
			log.Fatalf("failed to create minio client: %v", err)
		}

		online := client.IsOnline()
		if online {
			logrus.Infof("minio client connected to %s", props.Endpoint)
		} else {
			logrus.Errorf("minio client unconnected to %s", props.Endpoint)
		}

		minioClient = client
	})
}

// GetMinioClient 返回 minio client 实例（供上层仓库使用）
func GetMinioClient() *minio.Client {
	if minioClient == nil {
		panic("minioClient 未初始化")
	}
	return minioClient
}
